<?php

namespace app\common\taglib;
use think\template\TagLib;

class Sctaglib extends TagLib{
    /**
     * 定义标签列表
     */
    protected $tags   =  [
        'adv' => ['attr' => 'limit,order,where,item', 'close' => 1],
        'dcselect'            => ['attr' => '', 'close' => 0],
        'dcradio'             => ['attr' => '', 'close' => 0],
        'dccheckbox'             => ['attr' => '', 'close' => 0],
    ];

    /**
     * select标签解析
     * 格式：
     * {select options="list" name="" item="item" key="key" value="" class="" id=""}
     * @access public
     * @param array $tag 标签属性
     * @param string $content 标签内容
     * @return string
     */
    public function tagDcselect($tag, $content)
    {
        $list     = $this->autoBuildVar($tag['list']);
        $name     = isset($tag['name']) ? $tag['name'] : '';
        $class    = isset($tag['class']) ? $tag['class'] : '';
        $id       = isset($tag['id']) ? $tag['id'] : '';
        $default  = isset($tag['default']) ? $tag['default'] : '';
        $default = $this->autoCheckBuildVar($default);
        isset($tag['key']) or $tag['key'] = '';
        isset($tag['val']) or $tag['val'] = '';
        isset($tag['value']) or $tag['value'] = '';
        isset($tag['filter']) or $tag['filter'] = '';
        isset($tag['url']) or $tag['url'] = '';

        $parseStr = '<?php $_selected_val = '.$this->autoCheckBuildVar($tag['value']).';$_list = $_vals = []; if ('.$default.') '."\r\n";
        $parseStr .= '$_list[] = ["key" => "", "val" => '.$default.'] and $_vals[""] = '.$default.'; $_n = 0; foreach(' . $list . ' as $_key => $_val) { $_n++; $_item = [];';
        $parseStr .= "\r\n";
        $parseStr .= $tag['key'] ? '$_item["key"] = $_val["'.$tag['key'].'"]' : '$_item["key"] = $_key';
        $parseStr .= ";\r\n";
        $parseStr .= $tag['val'] ? '$_item["val"] = $_val["'.$tag['val'].'"]' : '$_item["val"] = $_val';
        $parseStr .= ";\r\n";
        $parseStr .= 'if(!$_list && $_selected_val."" === "" && $_n == 1) $_selected_val = $_item["key"]; ';
        $parseStr .= '$_list[] = $_item; $_vals[$_item["key"]] = $_item["val"]; } ?>';
        $parseStr .= "\r\n";

        /*$parseStr .= '<div class="sc-select '.$class.'"><?php echo $_vals[$_selected_val] ?? ""; ?></div>';*/
        // $parseStr .= "\r\n";
        // $parseStr .= '<select'. ($name ? ' name="'.$name.'"' : '').($id ? ' id="'.$id.'"' : '').($class ? ' class="'.$class.'"' : '').'>';
        // $parseStr .= "\r\n";

        $parseStr .= '<div class="sc-select '.$class.'" data-url="<?php echo '.$this->autoCheckBuildVar($tag['url']).';?>"> <?php echo $_vals[$_selected_val]; ?></div><select'. ($name ? ' name="'.$name.'"' : '').($id ? ' id="'.$id.'"' : '').($class ? ' class="'.$class.'"' : '').'>';

        $parseStr .= '<?php foreach($_list as $_key => $_item) { ?>';
        $parseStr .= "\r\n";
        $parseStr .= '<option value="<?php echo $_item["key"];?>" ';
        $parseStr .= "\r\n";
        $parseStr .= '<?php if($_item["key"]."" === $_selected_val."") { echo "selected";} ?>';
        $parseStr .= "\r\n";
        $parseStr .= '><?php echo $_item["val"];?></option>';
        $parseStr .= "\r\n";
        $parseStr .= '<?php } ?>';
        $parseStr .= "\r\n";
        $parseStr .= '</select>';

        return $parseStr;
    }

    /**
     * radio标签解析
     * 格式：
     * {dcradio options="list" name="" item="item" key="key" value="" class="" id=""}
     * @access public
     * @param array $tag 标签属性
     * @param string $content 标签内容
     * @return string
     */
    public function tagDcradio($tag, $content)
    {
        $list     = $this->autoBuildVar($tag['list']);
        $name     = isset($tag['name']) ? $tag['name'] : '';
        $class    = isset($tag['class']) ? $tag['class'] : '';
        $id       = isset($tag['id']) ? $tag['id'] : '';
        $radio_class    = isset($tag['radio_class']) ? $tag['radio_class'] : '';
        $radio_id       = isset($tag['radio_id']) ? $tag['radio_id'] : '';
        $default  = isset($tag['default']) ? $tag['default'] : '';
        $default = $this->autoCheckBuildVar($default);
        isset($tag['key']) or $tag['key'] = '';
        isset($tag['val']) or $tag['val'] = '';
        isset($tag['value']) or $tag['value'] = '';
        isset($tag['filter']) or $tag['filter'] = '';

        $parseStr = '<?php $_selected_val = '.$this->autoCheckBuildVar($tag['value']).';$_list = []; if ('.$default.') $_list[] = ["key" => "", "val" => '.$default.']; foreach(' . $list . ' as $_key => $_val) { $_item = [];';
        $parseStr .= "\r\n";
        $parseStr .= $tag['key'] ? '$_item["key"] = $_val["'.$tag['key'].'"]' : '$_item["key"] = $_key';
        $parseStr .= ";\r\n";
        $parseStr .= $tag['val'] ? '$_item["val"] = $_val["'.$tag['val'].'"]' : '$_item["val"] = $_val';
        $parseStr .= ";\r\n";
        $parseStr .= '$_list[] = $_item;} ?>';
        $parseStr .= "\r\n";
        $parseStr .= '<div class="dc-radio-container">';
        $parseStr .= "\r\n";
        $parseStr .= '<?php $n = 0; foreach($_list as $_key => $_item) { $n++; ?>';
        $parseStr .= "\r\n";
        $parseStr .= '<label class="dc-radio"> <input type="radio" '. ($name ? ' name="'.$name.'"' : '').' value="<?php echo $_item["key"];?>" ';
        $parseStr .= "\r\n";
        $parseStr .= '<?php if($_item["key"] == $_selected_val) { echo "checked";} ?>';
        $parseStr .= "\r\n";
        $parseStr .= ' /><div '.($radio_id ? ' id="dc-radio_'.$name.'_'.$id.'"' : '').($radio_class ? ' class="'.$radio_class.'"' : '').'><?php echo $_item["val"];?></div><?php if (count($_list) == $n + 1) echo \'<span><label id="'.$name.'-error" style="display:none;" class="error" for="'.$name.'"></label></span>\';?></label>';
        $parseStr .= "\r\n";
        $parseStr .= '<?php } ?></div>';

        return $parseStr;
    }
    /**
     * radio标签解析
     * 格式：
     * {dcradio options="list" name="" item="item" key="key" value="" class="" id=""}
     * @access public
     * @param array $tag 标签属性
     * @param string $content 标签内容
     * @return string
     */
    public function tagDccheckbox($tag, $content)
    {
        $list     = $this->autoBuildVar($tag['list']);
        $name     = isset($tag['name']) ? $tag['name'] : '';
        $class    = isset($tag['class']) ? $tag['class'] : '';
        $id       = isset($tag['id']) ? $tag['id'] : '';
        $value    = isset($tag['value']) ? $tag['value'] : '[]';
        isset($tag['key']) or $tag['key'] = '';
        isset($tag['val']) or $tag['val'] = '';
        $id       = isset($tag['id']) ? $tag['id'] : '';
        $value or $value = '[]';

        $parseStr = '<?php $n = 0; foreach(' . $list . ' as $_key => $_val) { $n++; ?>';
        $keyVar = ($tag['key'] ? '$_val["'.$tag['key'].'"]' : '$_key');
        $parseStr .= '<label class="dc-checkbox"> <input type="checkbox" '. ($name ? ' name="'.$name.'"' : '').' value="<?php echo '.$keyVar.';?>" ';
        $valueStr = $this->autoCheckBuildVar($value);
        if($tag['value']) $parseStr .= '<?php if(is_array('.$valueStr.') && in_array('.$keyVar.','.$valueStr.')) { echo "checked";} ?>';
        $parseStr .= ' /><div '.($id ? ' id="'.$id.'"' : '').($class ? ' class="'.$class.'"' : '').'><?php echo '.($tag['val'] ? '$_val["'.$tag['val'].'"]' : '$_val').';?></div><?php if (count('.$list.') == $n) echo \'<span><label id="'.$name.'-error" style="display:none;" class="error" for="'.$name.'"></label></span>\';?></label>';
        $parseStr .= '<?php } ?>';

        return $parseStr;
    }

    public function autoCheckBuildVar($value)
    {
        $flag = $value ? $value{0} : '';
        if ('$' == $flag || ':' == $flag) {
            $value = parent::autoBuildVar($value); // TODO: Change the autogenerated stub
        } elseif ('[' === $flag) {
        } else {
            $value = '\'' . $value . '\'';
        }
        return $value;
    }

    public function tagAdv($tag, $content) {
        $order = !empty($tag['order']) ? $tag['order'] : ''; //排序
        $limit = !empty($tag['limit']) ? $tag['limit'] : '1';
        $where = !empty($tag['where']) ? $tag['where'] : ''; //查询条件
        $item = !empty($tag['item']) ? $tag['item'] : 'item'; // 返回的变量item
        $key = !empty($tag['key']) ? $tag['key'] : 'key'; // 返回的变量key
        $ap_id = !empty($tag['ap_id']) ? $tag['ap_id'] : '0'; // 返回的变量key

        $str = '<?php ';
        $str .= '$ap_id =' . $ap_id . ';';
        $str .= '$ad_position = db("advposition")->cache(3600)->column("ap_id,ap_name,ap_width,ap_height","ap_id");';
        $str .= '$result = db("adv")->where("ap_id=$ap_id  and adv_enabled = 1 and adv_startdate < ' . strtotime(date('Y-m-d H:00:00')) . ' and adv_enddate > ' . strtotime(date('Y-m-d H:00:00')) . ' ")->order("adv_sort desc")->cache(3600)->limit("' . $limit . '")->select();';
        $str .= '
if(!in_array($ap_id,array_keys($ad_position)) && $ap_id)
{
  db("advposition")->insert(array(
         "ap_id"=>$ap_id,
         "ap_name"=>request()->module()."/".request()->controller()."/".request()->action()."页面自动增加广告位 $ap_id ",
  ));
  $ad_position[$ap_id]=array();
  \think\Cache::clear();
}


$c = ' . $limit . '- count($result); //  如果要求数量 和实际数量不一样 并且编辑模式
if($c > 0 && input("get.edit_ad"))
{
    for($i = 0; $i < $c; $i++) // 还没有添加广告的时候
    {
      $result[] = array(
          "adv_id" => 0,
          "adv_code" => "/public/images/not_adv.jpg",
          "adv_link" => ADMIN_SITE_URL."/Adv/adv_add/ap_id/$ap_id.html",
          "adv_title"   =>"暂无广告图片",
          "not_adv" => 1,
          "adv_target" => "_self",
          "ap_id"   =>$ap_id,
      );
    }
}

foreach($result as $' . $key . '=>$' . $item . '):

    $'.$item. '["position"] = $ad_position[$' . $item . '["ap_id"]];
    $'.$item. '["adv_link"] = HOME_SITE_URL."/Advclick/Advclick/adv_id/".$' . $item . '["adv_id"].".html";
    $'.$item. '["adv_target"] = "_blank";
    if(input("get.edit_ad") && !isset($' . $item . '["not_adv"]) )
    {

        $' . $item . '["style"] = "filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity: 0.5"; // 广告半透明的样式
        $' . $item . '["adv_link"] = ADMIN_SITE_URL."/Adv/adv_edit/adv_id/".$' . $item . '[\'adv_id\'].".html";
        $' . $item . '["adv_title"] = $ad_position[$' . $item . '["ap_id"]]["ap_name"]."===".$' . $item . '["adv_title"];
        $' . $item . '["adv_target"] = "_self";
        $' . $item . '["adv_style"] = "filter:alpha(opacity=30); -moz-opacity:0.3; -khtml-opacity: 0.3; opacity: 0.3";
    }
    ?>';
        $str .= $content;
        $str .= '<?php endforeach; ?>';
        if (!empty($str)) {
            return $str;
        }
        return;
    }
}

